import React from 'react';
import './index.less';
import Page from '@src/containers/Page';
import TableLayout from '@src/layouts/TableLayout';
import ActionLayout from '@src/layouts/ActionLayout';
import Block from '@src/components/Block';
import { asyncDelConfirm, asyncForm, asyncSMessage } from '@src/services/AsyncTools';
import { System } from '../../../../stores/system';

const actionList = [
  {
    key: 'add',
    name: '新增',
  },
  {
    key: 'edit',
    name: '编辑',
    selectNum: 1,
  },
  {
    key: 'del',
    name: '删除',
    needSelect: 1,
  },
];

const itemList = [
  {
    key: 'id',
    type: 'hidden',
  },
  {
    key: 'username',
    name: '用户名',
    type: 'input',
    placeholder: '请输入用户名',
    require: true,
  },
];

export default class extends Page {
  init() {
    this.columns = [
      {
        title: '用户名',
        dataIndex: 'username',
      },
    ];
  }

  initData() {
    System.listManager(this.state.search).then(result => {
      this.setTableData(result.list, result.total);
    });
  }

  addAction() {
    asyncForm('新增', itemList, {}, data => {
      return System.addManager(data).then(() => {
        asyncSMessage('新增成功!');
        this.refresh();
      });
    });
  }

  editAction() {
    const { selectedRows } = this.state;
    asyncForm('编辑', itemList, selectedRows[0], data => {
      return System.putManager(data).then(() => {
        asyncSMessage('编辑成功!');
        this.refresh();
      });
    });
  }

  delAction() {
    const { selectedKeys } = this.state;
    asyncDelConfirm('删除确认', '是否删除选中账号?', () => {
      Promise.all(selectedKeys.map(row => System.delManager({ id: row }))).then(() => {
        asyncSMessage('删除成功!');
        this.refresh();
      });
    });
  }

  renderView() {
    return (
      <Block flex>
        <ActionLayout
          itemList={actionList}
          selectedKeys={this.state.selectedKeys}
          onAction={key => this.onAction(key)}
        />
        <TableLayout
          select
          columns={this.columns}
          list={this.state.list}
          pagination={this.state.page}
          loading={this.props.core.loading}
          onChange={(pagination, filters, sorter) => this.tableChange(pagination, filters, sorter)}
          onSelect={(keys, rows) => this.tableSelect(keys, rows)}
          selectedKeys={this.state.selectedKeys}
        />
      </Block>
    );
  }
}
